﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SharpSoft.Data.DAOS
{
    public class ServerFileDAO : SharpSoft.Data.DAOS.DAO
    {
        protected override string InitScriptFileName => "serverfile.txt";

        public ServerFileDAO(Database p_db, int p_userid) : base(p_db, p_userid) { }
        public int InsertServerFile(int userid, int? folderid, string name, string originalName, string hash, string tag, string remark)
        {
            var sql = $@"INSERT INTO `Server_Files`(`userid`,`folderid`,`name`,`originalName`,`extensionName`,`hash`,`tag`,`remark`)VALUES(@userid,@folderid,@name,@originalName,@extensionName,@hash,@tag,@remark);SELECT LAST_INSERT_ID();";
            var extensionName = System.IO.Path.GetExtension(originalName);
            if (extensionName != null)
            {
                extensionName = extensionName.ToLower();
            }
            return db.ExecuteInt32(sql, new { userid, folderid, name, originalName, extensionName, hash, tag, remark });
        }

        /// <summary>
        /// 更新文件信息
        /// </summary>
        /// <param name="fileid"></param>
        /// <param name="originalName"></param>
        /// <param name="hash"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public int UpdateServerFile(int fileid, string originalName, string hash, string remark)
        {
            var extensionName = System.IO.Path.GetExtension(originalName);
            if (extensionName != null)
            {
                extensionName = extensionName.ToLower();
            }
            var sql = $@"UPDATE `Server_Files` SET `originalName`=@originalName,`updateTime`=NOW(),`extensionName`=@extensionName,`hash`=@hash,`remark`=@remark  WHERE `fileid`=@fileid;";
            return db.ExecuteNonQuery(sql, new { fileid, originalName, extensionName, hash, remark });
        }
        /// <summary>
        /// 改变文件的文件夹
        /// </summary>
        /// <param name="fileid"></param>
        /// <param name="folderid"></param>
        public void ChangeFolder(int fileid, int? folderid)
        {
            var sql = $@"UPDATE `Server_Files` SET `folderid`=@folderid WHERE `fileid`=@fileid;";
            db.ExecuteNonQuery(sql, new { fileid, folderid });
        }

        public int DeleteServerFile(int fileid)
        {
            var sql = $@"UPDATE `Server_Files` SET `isDelete`=TRUE,`deleteTime`=NOW()  WHERE `fileid`=@fileid;";
            return db.ExecuteNonQuery(sql, new { fileid });
        }
        /// <summary>
        /// 查询指定哈希值的文件是否存在
        /// </summary>
        /// <param name="hash"></param>
        /// <returns></returns>
        public bool ExistsFileHash(int? folderid, string hash, string tag, out int? fileid)
        {
            var sql = $@"SELECT `fileid` FROM `Server_Files` WHERE {(folderid.HasValue? "`folderid`=@folderid" : "`folderid` is NULL") } AND `hash`=@hash AND {(tag==null?"`tag` is NULL":"`tag`=@tag")};";
            fileid = db.ExecuteScalar<int?>(sql, new {  hash, folderid, tag });

            return fileid.HasValue;
        }
        /// <summary>
        /// 获取指定的服务器文件信息
        /// </summary>
        /// <param name="fileid"></param>
        /// <returns></returns>
        public ServerFileModel GetServerFile(int fileid)
        {
            var sql = $@"SELECT `fileid`,`userid`,`folderid`,`name`,`hash`,`originalName`,`uploadTime`,`updateTime`,`deleteTime`,`isDelete`,`extensionName`,`tag`,`remark` FROM `Server_Files` WHERE `fileid`=@fileid;";
            return db.ExecuteObject<ServerFileModel>(sql, new { fileid });
        }
        public ServerFileModel[] GetServerFiles(int[] ids)
        {
            if (ids == null || ids.Length == 0)
            {
                return new ServerFileModel[0];
            }
            var sql = $@"SELECT `fileid`,`userid`,`folderid`,`name`,`hash`,`originalName`,`uploadTime`,`updateTime`,`deleteTime`,`isDelete`,`extensionName`,`tag`,`remark` FROM `Server_Files` WHERE `fileid` IN ({string.Join(",", ids)});";
            return db.ExecuteArray<ServerFileModel>(sql);
        }
        public ServerFileModel GetServerFile(string filename)
        {
            var sql = $@"SELECT `fileid`,`userid`,`folderid`,`name`,`hash`,`originalName`,`uploadTime`,`updateTime`,`deleteTime`,`isDelete`,`extensionName`,`tag`,`remark` FROM `Server_Files` WHERE `name`=@filename;";
            return db.ExecuteObject<ServerFileModel>(sql, new { filename });
        }
        public SqlPagination<ServerFileModel> GetServerFilesByUser(int uid, int pageindex, int countOnPage)
        {
            var sql = $@"SELECT `fileid`,`userid`,`folderid`,`name`,`hash`,`originalName`,`uploadTime`,`updateTime`,`deleteTime`,`isDelete`,`extensionName`,`tag`,`remark` FROM `Server_Files` WHERE `userid`=@uid order by `uploadTime` DESC;";
            return db.ExecutePagination<ServerFileModel>(sql, countOnPage, pageindex, new { uid });
        }
        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="condition">查询条件</param>
        /// <param name="paras">参数</param>
        /// <param name="pageindex">页面索引</param>
        /// <param name="countOnPage">一页显示的数量</param>
        /// <returns></returns>
        public SqlPagination<ServerFileModel> GetServerFiles(string condition, object paras, int pageindex, int countOnPage)
        {
            var sql = $@"SELECT `fileid`,`userid`,`folderid`,`name`,`hash`,`originalName`,`uploadTime`,`updateTime`,`deleteTime`,`isDelete`,`extensionName`,`tag`,`remark` FROM `Server_Files` WHERE 1=1 {(string.IsNullOrWhiteSpace(condition) ? "" : $"AND {condition}")} order by `fileid` DESC;";
            return db.ExecutePagination<ServerFileModel>(sql, countOnPage, pageindex, paras);
        }


    }

    public class ServerFileModel
    {
        public int fileid { get; set; }
        /// <summary>
        /// 文件所属的用户
        /// </summary>
        public int userid { get; set; }
        /// <summary>
        /// 所属文件夹Id
        /// </summary>
        public int? folderid { get; set; }
        /// <summary>
        /// 文件的唯一随机名称
        /// </summary>
        public string name { get; set; }
        /// <summary>
        /// 获取用于访问该文件的名称
        /// </summary>
        public string visitName
        {
            get
            {
                return $"{fileid}_{name}";
            }
        }
        /// <summary>
        /// 原件hash值
        /// </summary>
        public string hash { get; set; }
        /// <summary>
        /// 原始文件名
        /// </summary>
        public string originalName { get; set; }
        /// <summary>
        /// 文件扩展名
        /// </summary>
        public string extensionName { get; set; }
        public DateTime uploadTime { get; set; }
        public DateTime updateTime { get; set; }
        public DateTime? deleteTime { get; set; }
        public bool isDelete { get; set; }
        /// <summary>
        /// 文件标签
        /// </summary>
        public string tag { get; set; }
        /// <summary>
        /// 文件备注
        /// </summary>
        public string remark { get; set; }
        /// <summary>
        /// 当前文件是否是图片
        /// </summary>
        public bool isImage
        {
            get
            {
                switch (this.extensionName)
                {
                    case ".jpg":
                    case ".jpeg":
                    case ".png":
                    case ".bmp":
                    case ".gif":
                    case ".tiff":
                    case ".ico":
                    case ".svg":
                    case ".webp":
                        return true;
                    default:
                        return false;
                }
            }
        }
    }






}
